#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import inspect
import logging
from logging.handlers import TimedRotatingFileHandler


class Logger(object):

    def __init__(self, logger_name='Framework'):
        self.logger = logging.getLogger(logger_name)
        logging.root.setLevel(logging.NOTSET)
        self.log_file_name = 'log.log'
        self.formatter = logging.Formatter('%(asctime)s - %(filename)s - <%(levelname)s>: %(message)s')
        self.console_output_level = 'INFO'
        self.file_output_level = 'DEBUG'
        self.backup_count = 5

    def get_logger(self):
        """在logger中添加日志句柄并返回，如果logger已有句柄，则直接返回"""
        if not self.logger.handlers:
            console_handler = logging.StreamHandler()
            console_handler.setLevel(self.console_output_level)
            console_handler.setFormatter(self.formatter)
            self.logger.addHandler(console_handler)
            # 利用日志回滚，每天创建一个日志文件，最多保留 backup_count 份
            file_handler = TimedRotatingFileHandler(filename=self.log_file_name, when='D', interval=1,
                                                    backupCount=self.backup_count, delay=True, encoding='utf-8')
            file_handler.setLevel(self.file_output_level)
            file_handler.setFormatter(self.formatter)
            self.logger.addHandler(file_handler)
        return self.logger

logger = Logger().get_logger()

if __name__ == '__main__':
    class A(object):
        @property
        def __name__(self):
            return inspect.stack()[1][3]

        @staticmethod
        def func_1(x):
            return x % 2 == 0

        @staticmethod
        def func_2(a, b):
            return a + b


    class B(A):
        def func_test(self, func_type, *args):
            func_dict = {
                "func_1": self.func_1,
                "func_2": self.func_2
            }
            try:
                func_result = func_dict[func_type](*args)
                return func_result
            except Exception as e:
                logger.error("Invoke " + func_type + " error: " + str(e), exc_info=True)

    logger.info("Create instance b of class B()")
    b1 = B()
    logger.info("Invoke instance method func_2")
    a1 = b1.func_test("func_3", "s")
    logger.info("Invoke instance method func_2")
    a2 = b1.func_test("func_2", "s", "b")


    print("a = " + str(a1))
    print("a = " + str(a2))
